<template>
  <a-modal title="新增" v-model="show" :maskClosable="false" :width="1050" placement="right" :closable="true"
    @cancel="onClose" :footer="null" :visiable="deviceInfoAddVisiable">
    <a-form :form="form">
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="设备编号" v-bind="formItemLayout">
            <a-input v-decorator="['deviceNo']" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="设备类型" v-bind="formItemLayout">
            <a-select mode="default" :allowClear="true" style="width: 100%" show-search placeholder="请选择"
              option-filter-prop="children" :filter-option="filterOption"
              v-decorator="['deviceType', { rules: [{ required: true, message: '必填' }] }]">
              <a-select-option key="1">终端机具</a-select-option>
              <a-select-option key="2">终端部件</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="终端厂商" v-bind="formItemLayout">
            <a-select show-search placeholder="请输入代码或名称" option-filter-prop="children" style="width: 100%"
              :allowClear="true" :filter-option="filterOption" @focus="selectBrandCode" @search="selectBrandCode"
              v-decorator="['brandCode', { rules: [{ required: true, message: '必填字段' }] }]">
              <a-select-option v-for="(d, index) in brandCodeData" :key="d.id">
                {{ d.id }}-{{ d.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="终端型号" v-bind="formItemLayout">
            <a-select show-search placeholder="请输入代码或名称" option-filter-prop="children" style="width: 100%"
              :allowClear="true" :filter-option="filterOption" @focus="selectByBrandCode" @search="selectByBrandCode"
              v-decorator="['modelCode', { rules: [{ required: true, message: '必填字段' }] }]">
              <a-select-option v-for="(d, index) in modelCodeData" :key="d.id">
                {{ d.id }}-{{ d.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="S/N号" v-bind="formItemLayout">
            <a-input placeholder="最长64位数字、字母"
              v-decorator="['sn', { rules: [{ required: true, validator: snValidator }] }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="入库方式" v-bind="formItemLayout">
            <a-select mode="default" :allowClear="true" style="width: 100%" show-search placeholder="请选择"
              option-filter-prop="children" :filter-option="filterOption"
              v-decorator="['libraryType', { rules: [{ required: true, message: '必填字段' }] }]">
              <a-select-option key="01">手动</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="入库批次号" v-bind="formItemLayout">
            <a-input placeholder="最长64位数字、字母"
              v-decorator="['libraryBatch', { rules: [{ required: true, message: '必填字段' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="有效期日期" v-bind="formItemLayout">
            <a-range-picker format="YYYYMMDD"
              v-decorator="['effectiveDate', { rules: [{ required: true, message: '必填字段' }] }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="联系人姓名" v-bind="formItemLayout">
            <a-input placeholder="最长32位汉字、字母和数字" v-decorator="['contactName']" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="联系电话" v-bind="formItemLayout">
            <a-input placeholder="最长11位数字" v-decorator="['contactPhone']" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="联系人电子邮箱" v-bind="formItemLayout">
            <a-input placeholder="最长128位字符、字母和数字"
              v-decorator="['contactEmail', { rules: [
                { required: true, message: '请输入正确的邮箱' },
                { type: 'email', message: '请输入正确的邮箱' },
              ] }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="联系地址" v-bind="formItemLayout">
            <a-textarea allow-clear placeholder="最长128位字符、字母和汉字" v-decorator="['contactAddr']" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="设备描述" v-bind="formItemLayout">
            <a-textarea placeholder="最长128位字符、字母和汉字"
              v-decorator="['deviceDesc', { rules: [{ required: true, message: '必填' }] }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="设备购置方式" v-bind="formItemLayout">
            <a-select mode="default" :allowClear="true" style="width: 100%" show-search placeholder="请选择"
              option-filter-prop="children" :filter-option="filterOption"
              v-decorator="['devicePurchType', { rules: [{ required: true, message: '必填' }] }]">
              <a-select-option key="00">自有</a-select-option>
              <a-select-option key="01">租用</a-select-option>
              <a-select-option key="02">第三方所有</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="设备单价（元）" v-bind="formItemLayout">
            <a-textarea placeholder="最长20数字、字符"
              v-decorator="['devicePrice', { rules: [{ required: true, validator: devicePriceValidator }] }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="设备状态" v-bind="formItemLayout">
            <a-select mode="default" :allowClear="true" style="width: 100%" show-search placeholder="请选择"
              option-filter-prop="children" :filter-option="filterOption"
              v-decorator="['status', { rules: [{ required: true, message: '必填' }] }]">
              <a-select-option key="10">未使用</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="租赁商户编码" v-bind="formItemLayout">
            <a-input v-decorator="['mchntNo']" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="关联虚拟终端编号" v-bind="formItemLayout">
            <a-input allow-clear placeholder="最长20位数字、字母" v-decorator="['termNo']" :disabled="true" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="租赁日期" v-bind="formItemLayout">
            <a-range-picker format="YYYYMMDD" v-decorator="['leaseDate']" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="租赁费用(元/日)" v-bind="formItemLayout">
            <a-input placeholder="最长20数字、字符" v-decorator="['deviceLeasePrice']" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="押金(元)" v-bind="formItemLayout">
            <a-input placeholder="最长20数字、字符" v-decorator="['cashPledge']" />
          </a-form-item>
        </a-col>
      </a-row>
      <br>

    </a-form>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-modal>
</template>
<script>
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 }
}
export default {
  name: 'deviceInfoAdd',
  props: {
    deviceInfoAddVisiable: {
      default: false
    },
    instId: '',
  },
  data() {
    return {
      brandCodeData: [],
      modelCodeData: [],
      loading: false,
      msgPushKeyShow: false,
      bindUserIdShow: false,
      formItemLayout,
      form: this.$form.createForm(this),
      validateStatus: '',
      // firstValue: {},
      info: {
        infoName: '',
        remark: '',
        menuId: ''
      }
    }
  },
  computed: {
    show: {
      get: function () {
        return this.deviceInfoAddVisiable
      },
      set: function () {
      }
    }
  },
  mounted() {

  },

  methods: {
    devicePriceValidator(rule, value, callback) {
      if (!value) {
        callback(new Error('必填'))
      } else {
        callback(value ? (/(^[A-Za-z0-9]{1,20}$)/.test(value) ? undefined : new Error('请输入正确的格式')) : undefined)
      }
    },
    EmailValidator(rule, value, callback) {
      if (!value) {
        callback(new Error('必填'))
      } else {
        callback(value ? (/(^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$)/.test(value) ? undefined : new Error('请输入正确的邮箱格式')) : undefined)
      }
    },
    snValidator(rule, value, callback) {
      if (!value) {
        callback(new Error('必填'))
      } else {
        callback(value ? (/(^[a-zA-Z0-9]{1,64}$)/.test(value) ? undefined : new Error('请输入正确的格式')) : undefined)
      }
    },
    selectBrandCode(val) {
      this.brandCodeData = []
      let param = {}
      if (val) {
        param = {
          q: encodeURIComponent(val + `&${this.instId}`),
          pageSize: 20
        }
      } else {
        param = {
          q: encodeURIComponent(`&${this.instId}`),
          pageSize: 20
        }
      }
      this.$get('terminalAdmin/termbrandSelect2List', param).then((r) => {
        let result = r.data.results
        result.forEach(r => {
          this.brandCodeData.push(r);
        })
      })
    },

    selectByBrandCode(val) {
      this.modelCodeData = []
      let brandCode = this.form.getFieldsValue(['brandCode'])
      if (brandCode.brandCode) {
        let param = {}
        if (val) {
          param = {
            q: encodeURIComponent(val + `&${brandCode.brandCode}` + `&${this.instId}`),
            pageSize: 20
          }
        } else {
          param = {
            q: encodeURIComponent(`&${brandCode.brandCode}` + `&${this.instId}`),
            pageSize: 20
          }
        }
        this.$get('modelAdmin/termmodelSelect2List', param).then((r) => {
          let result = r.data.results
          result.forEach(r => {
            this.modelCodeData.push(r);
          })
        })

      } else {
        this.$message.warning('请先选择终端产商')
      }
    },

    getMoment(value) {
      return this.$moment(value).format('YYYYMMDD')
    },

    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },

    reset() {
      this.loading = false
      this.form.resetFields()
    },
    onClose() {
      this.msgPushKeyShow = false
      this.bindUserIdShow = false
      this.reset()
      this.$emit('close')
    },
    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.setInfoFields()
          this.loading = true
          this.info.instId = this.instId
          this.info.startDate = this.getMoment(this.info.effectiveDate[0])
          this.info.endDate = this.getMoment(this.info.effectiveDate[1])
          let leaseDate = this.info.leaseDate
          // console.log(leaseDate)
          if (leaseDate) {
            this.info.leaseStartDate = this.getMoment(this.info.leaseDate[0])
            this.info.leaseEndDate = this.getMoment(this.info.leaseDate[1])
          }
          this.info.optFlag = 'add'

          // console.log(this.info)
          this.$post('deviceInfo', {
            ...this.info
          }).then((r) => {
            this.reset()
            this.$emit('success')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },

    setInfoFields() {
      let values = this.form.getFieldsValue(['deviceNo', 'deviceType', 'brandCode', 'modelCode', 'sn', 'libraryType',
        'libraryBatch', 'effectiveDate', 'contactName', 'contactPhone', 'contactEmail', 'contactAddr', 'deviceDesc',
        'status', 'devicePurchType', 'devicePrice', 'mchntNo', 'termNo', 'leaseDate', 'deviceLeasePrice', 'cashPledge'])
      if (typeof values !== 'undefined') {
        Object.keys(values).forEach(_key => {
          this.info[_key] = values[_key]
        })
      }
    }


  }

}
</script>

